package com.mingyong.peephelper;



import java.io.*;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;

public class PeepHelper extends Activity implements OnClickListener {
	private static final String LOG_TAG = "PEEPHELPER";

	boolean root = false;
	String backupfiledir = "/data/data/com.mingyong.peephelper/databases";
	String backupfilename = backupfiledir + "/backup.db";
	String dbfile = "/data/data/com.htc.htctwitter/databases/htcchirp.db";
	String peepdir = "";
	Button btn_ok;
	Button btn_restore;
	TextView txtUsername;
	TextView txtPassword;
	TextView txtApiurl;
	TextView txtMessage;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// runRootCommand
		try {
			Runtime.getRuntime().exec("su");
			root = true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (!root) {
			return;
		}
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// Mysms ss = new Mysms(this);
		btn_ok = (Button) this.findViewById(R.id.ButtonOK);
		btn_restore = (Button) this.findViewById(R.id.ButtonRestore);
		btn_ok.setOnClickListener(this);
		txtMessage = (TextView) this.findViewById(R.id.TextViewMessage);
		peepdir = getPeepPath();
		if (peepdir==null)
		{
			txtMessage.setText(R.string.notinstall);
		}
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if (peepdir==null)
			return;
		if (arg0.getId() == btn_ok.getId()) {
			
			
			txtUsername = (TextView) this.findViewById(R.id.EditUsername);
			txtPassword = (TextView) this.findViewById(R.id.EditPassword);
			txtApiurl = (TextView) this.findViewById(R.id.EditApiurl);
			String sUsername = txtUsername.getText().toString();
			String sPassword = txtPassword.getText().toString();
			String sApiurl = txtApiurl.getText().toString();

			if (sUsername == null || "".equals(sUsername) || sPassword == null
					|| "".equals(sPassword) || sApiurl == null
					|| "".equals(sApiurl)) {
				txtMessage.setText(R.string.parameter_error);
				return;
			}
			sApiurl = sApiurl.toLowerCase();
			if (sApiurl.startsWith("http://")) {
				sApiurl = sApiurl.substring(7);
			}
			if (!sApiurl.endsWith("/")) {
				sApiurl += "/";
			}
			if (sApiurl.length() < 2) {
				txtMessage.setText(R.string.parameter_error);
				return;
			}
			File datadir = Environment.getDataDirectory();

			String dataPath = datadir.getAbsolutePath();
			dataPath += "/data";
			Log.d(LOG_TAG, dataPath);
			
			dbfile = dataPath + "/" + peepdir + "/databases/htcchirp.db";
			Log.d(LOG_TAG, dbfile);
			boolean b = false;
			if (fileExists(backupfilename)) {
				File f = new File(backupfilename);
				f.delete();

			}
			touchDb();

			if (copyFile(dbfile, backupfilename)) {
				// txtMessage.setText(R.string.success);
				// backed=true;
			} else {
				Log.e(LOG_TAG, "backup fail");
				txtMessage.setText(R.string.fail);
				return;
			}

			SQLiteDatabase sld = this.openOrCreateDatabase("backup.db",
					MODE_PRIVATE, null);
			/*
			 * Cursor cursor =
			 * sld.rawQuery(" select * from accounts where username='"
			 * +txtUsername.getText(),null); if (cursor.getCount()>0) {
			 * 
			 * } else {
			 * 
			 * }
			 */
			// cursor.close();
			Log.e(LOG_TAG, "open db");
			String sql0 = "update accounts set defaultaccount=0";

			String sql = "insert into accounts(username,user_id,password,apiurl,enablessl,defaultaccount,finish_setup) ";
			sql = sql + " values('" + sUsername + "','" + sUsername + "','";
			sql = sql + txtPassword.getText() + "','" + sApiurl + "',0,1,1)";
			try {
				Log.e(LOG_TAG, "ready to go");
				sld.execSQL(sql0);
				sld.execSQL(sql);
				sld.close();
				Log.e(LOG_TAG, "ready to copy " + backupfilename + " to "
						+ dbfile);
				if (copyFile(backupfilename, dbfile)) {
					Log.e(LOG_TAG, "ok to copy " + backupfilename + " to "
							+ dbfile);
					b = true;
				}
			} catch (Exception e) {
				Log.e(LOG_TAG, "onClick" + e.toString());
			} finally {

			}
			
			b = runRootCommand(new String[]{"/system/bin/chmod 666 " + dbfile});
			
			if (b)
				txtMessage.setText(R.string.success);
			else
				txtMessage.setText(R.string.fail);

		} else if (arg0.getId() == btn_restore.getId()) {

		}
	}

	public String getPeepPath() {
		Process process = null;
		DataOutputStream os = null;
		DataInputStream is = null;
		String[] commands = new String[] { "/system/bin/ls /data/data" };
		String sRet=null;
		try {
			// Getting Root ;)
			process = Runtime.getRuntime().exec("su");
			os = new DataOutputStream(process.getOutputStream());
			is = new DataInputStream(process.getInputStream());
			// Doing Stuff ;)
			for (String single : commands) {
				os.writeBytes(single + "\n");
				os.flush();
				Log.d(LOG_TAG, single);
			}

			os.writeBytes("exit\n");
			os.flush();

			
			while (true) {
				sRet = is.readLine();
				if (sRet == null)
					break;
				if (sRet.toLowerCase().equals("com.htc.htctwitter")) {
					break;
				}
			}
			
			
			Thread.sleep(2000);
			process.waitFor();

		} catch (Exception e) {

			Log.d(LOG_TAG, "Unexpected error - Here is what I know: "
					+ e.getMessage());
			return null;
		} finally {
			Log.d(LOG_TAG, "FINALLY");
			try {
				if (os != null) {
					os.close();
				}
				if (is!=null)
				{
					is.close();
				}
				process.destroy();
			} catch (Exception e) {
				// nothing
			}
		}

		return sRet;

	}

	public boolean copyFile(String source, String dest) {
		boolean b = false;
		if (fileExists(source)) {
			// file not exists. begin to backup
			Log.e(LOG_TAG, "1 copy " + source + " to " + dest);
			try {
				FileInputStream fis = new FileInputStream(source);

				File f = new File(dest);
				if (fileExists(dest)) {
					f.delete();
				}
				f.createNewFile();
				Log.e(LOG_TAG, "2 copy " + source + " to " + dest);
				FileOutputStream fos = new FileOutputStream(f);
				byte[] buffer = new byte[4096];
				while (true) {
					int read = fis.read(buffer, 0, 4096);
					if (-1 == read)
						break;
					fos.write(buffer, 0, read);
				}
				fis.close();
				fos.flush();
				fos.close();
				b = true;
				Log.e(LOG_TAG, "3 copy " + source + " to " + dest);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Log.e(LOG_TAG, "4 copyFile" + e.toString());

			}
		} else {
			Log.e(LOG_TAG, "5 copyFile source not exist." + source);
		}
		return b;
	}

	public boolean dirExists(String path) {
		boolean b = false;
		File f = new File(path);
		if (f.exists()) {
			if (f.isDirectory()) {
				b = true;
			}
		}
		return b;
	}

	public boolean fileExists(String path) {
		boolean b = false;
		try {
			FileInputStream fis = new FileInputStream(path);
			fis.close();
			fis = null;
			b = true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.e(LOG_TAG, "fileExists " + e.toString());
		}
		return b;
	}

	public void touchDb() {
		try {
			SQLiteDatabase slb = this.openOrCreateDatabase("test.db",
					MODE_PRIVATE, null);
			slb.close();
		} catch (Exception e) {
			Log.e(LOG_TAG, "touchDb" + e.toString());
		}
	}

	public static boolean runRootCommand(String[] commands) {

		Process process = null;
		DataOutputStream os = null;
		DataInputStream is = null;
		try {
			// Getting Root ;)
			process = Runtime.getRuntime().exec("su");

			os = new DataOutputStream(process.getOutputStream());
			is = new DataInputStream(process.getInputStream());
			// Doing Stuff ;)
			for (String single : commands) {
				os.writeBytes(single + "\n");
				os.flush();
				Log.d(LOG_TAG, single);
			}

			os.writeBytes("exit\n");
			os.flush();

			
			Thread.sleep(2000);
			process.waitFor();

		} catch (Exception e) {

			Log.d(LOG_TAG, "Unexpected error - Here is what I know: "
					+ e.getMessage());
			return false;
		} finally {
			Log.d(LOG_TAG, "FINALLY");
			try {
				if (os != null) {
					os.close();
				}
				process.destroy();
			} catch (Exception e) {
				// nothing
			}
		}

		return true;

	}
}